# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # root为p 返回p
        # root为q 返回q
        # root为none 返回root
        if root == p or root == q or root is None:
            return root

        # 递归左右节点
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        # 都不为空，返回root
        if left and right:
            return root

        # 一边为空，返回另一边有值的
        if left and not right:
            return left
        elif right and not left:
            return right
        else:
        # 其余情况返回none
            return None


